<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/16
 * Time: 17:58
 */

namespace app\common\model\curriculum;


use app\admin\model\PageResponse;
use app\common\model\dynamic\DynamicFlowItem;
use app\common\model\dynamic\DynamicFlowItemTeacher;
use app\common\model\DynamicFlow;
use app\common\model\IMakeDynamicFlow;
use app\common\model\teacher\Teacher;
use app\common\utils\ObjectUtil;
use think\Db;
use think\Exception;
use think\Model;

/**
 * @deprecated
 * Class Curriculum
 * @package app\common\model\curriculum
 *
 * @property integer curriculum_id
 * @property integer curriculum_class
 * @property string curriculum_name
 * @property string curriculum_description
 * @property string curriculum_pic
 * @property integer curriculum_sales
 * @property integer curriculum_addtime
 * @property integer curriculum_updatetime
 * @property string curriculum_sale_price
 * @property string curriculum_market_price
 * @property string curriculum_icon
 * @property boolean hide
 * @property string curriculum_summary
 * @property integer curriculum_type
 * @property integer curriculum_level
 * @property integer curriculum_suit_user
 * @property integer curriculum_episode_number
 * @property double comment_score
 * @property integer sales_volume
 * @property integer credit_cost
 * @property integer enable_pay_type
 *
 * @property string apple_pay_price
 * @property string apple_pay_production_id
 *
 */
class Curriculum extends Model implements IMakeDynamicFlow
{
    protected $table = 'curriculum';
    protected $pk = 'curriculum_id';

    private static $SaveFields = [
        'curriculum_class',
        'curriculum_name',
        'curriculum_description',
        'curriculum_pic',
        'curriculum_sales',
        'curriculum_addtime',
        'curriculum_updatetime',
        'curriculum_sale_price',
        'curriculum_market_price',
        'curriculum_icon',
        'curriculum_summary',
        'curriculum_type',
        'curriculum_level',
        'curriculum_suit_user',
        'buy_total',
        'hide',
        'credit_cost',
        'enable_pay_type',
        'apple_pay_price',
        'apple_pay_production_id',
    ];
    public static function getSaveFields() : array {
        return self::$SaveFields;
    }

    public static function manageList(int $limit, int $offset, int $class_id = 0, $keywords = null) :PageResponse {

        $filter = '';
        $params = ['limit' => $limit, 'offset' => $offset, ];

        if ($class_id > 0) {
            $filter .= ' AND c.curriculum_class=:class_id ';
            $params['class_id'] = $class_id;
        }
        if ($keywords) {
            $filter .= ' AND c.curriculum_name LIKE :kw ';
            $params['kw'] = "%$keywords%";
        }

        $sql = <<<SQL
SELECT c.*, s.sales_title,
  (SELECT rec_id FROM recommend r WHERE c.curriculum_id=r.rec_item_id AND r.rec_item_type=2) 
FROM curriculum c
LEFT JOIN sales s ON s.sales_id=c.curriculum_sales
WHERE TRUE {$filter}
ORDER BY c.curriculum_id DESC 
LIMIT :limit OFFSET :offset
SQL;
        $list = Db::query($sql, $params);

        $sql = <<<SQL
SELECT count(curriculum_id) as num FROM curriculum
WHERE TRUE {$filter}
SQL;
        unset($params['limit'], $params['offset']);
        $re = Db::query($sql, $params);
        $total = $re[0]['num'] ?? 0;

        return PageResponse::success($list, $total);
    }

    public static function names() {
        $sql = <<<SQL
SELECT curriculum_id AS id ,curriculum_name AS name, curriculum_sale_price price FROM curriculum 
SQL;
        $list = Db::query($sql);
        
        return $list;
    }

    /**
     * 检查分类是否使用了
     *
     * @param $class_id
     * @return bool
     */
    public static function classUsed($class_id) {
        $sql = <<<SQL
SELECT exists(SELECT * FROM curriculum WHERE curriculum_class=:class_id LIMIT 1) AS e
SQL;
        $re = Db::query($sql, ['class_id' => $class_id]);

        return $re[0]['e'] ?? false;
    }

    /**
     * 设置隐藏属性
     * @param $id
     * @param $hide
     */
    public static function setHide($id, $hide) {
        Db::transaction(function () use ($id,$hide) {
            $sql = <<<SQL
UPDATE curriculum SET hide = :hide WHERE curriculum_id = :id RETURNING *
SQL;
            $re = Db::query($sql, ['id' => $id, 'hide' => $hide]);
            if (empty($re)) return;

            /**
             * @var static $model
             */
            $model = ObjectUtil::assign(static::class, $re[0]);

            if ($hide) {
                DynamicFlow::del(DynamicFlow::CLASS_CURRICULUM, $model->curriculum_id);
            } else {
                $model->makeDynamicData(false,DynamicFlow::SOURCE_ADMIN);
            }
        });
    }

    /**
     * 统计计算课程的视频数
     * @param $id
     */
    public static function countVideos($id) {
        $sql = <<<SQL
UPDATE curriculum
SET curriculum_episode_number = (
  SELECT count(v.*) num
  FROM curriculum_video v
  WHERE v.video_curriculum = curriculum_id AND v.hide=FALSE 
)
WHERE curriculum_id = :id;
SQL;
        Db::execute($sql, ['id' => $id]);
    }

    /**
     * 产生老师动态
     *
     * @param bool $isNew
     * @param integer $source
     * @return DynamicFlow
     * @throws Exception
     */
    public function makeDynamicData(bool $isNew, int $source = DynamicFlow::SOURCE_SYSTEM): DynamicFlow
    {
        $sql = 'select video_teacher tid from curriculum_video where video_curriculum=:cid AND hide=FALSE limit 1';
        $re = Db::query($sql, ['cid' => $this->curriculum_id]);
        if (empty($re)) {
            throw new Exception('课程没有视频上架');
        }
        $teacher = Teacher::get($re[0]['tid']);
        if (empty($teacher)) {
            throw new Exception('数据错误，不正确的老师id');
        }

        $dynamic = new DynamicFlow();
        $dynamic->df_time = time();
        $dynamic->df_source = $source;
        $dynamic->df_isfee = false;
        $dynamic->df_isnew = $isNew;

        $item = new DynamicFlowItem();
        $item->item_id = (int) $this->curriculum_id;
        $item->item_title = $this->curriculum_name;
        $item->item_cover = $this->curriculum_pic;
        $item->item_summary = $this->curriculum_summary;

        $item_teacher = new DynamicFlowItemTeacher();
        $item_teacher->teacher_id = (int) $teacher->id;
        $item_teacher->teacher_name = $teacher->realname;
        $item_teacher->teacher_avatar = $teacher->avatar ?? Teacher::DEFAULT_AVATAR;
        $item_teacher->teacher_degree = $teacher->getDegreeName();
        $item->item_teacher = $item_teacher;

        $dynamic->df_class = DynamicFlow::CLASS_CURRICULUM;
        $dynamic->df_type = DynamicFlow::TYPE_CURRICULUM;

        $dynamic->df_value = $item;

        $dynamic->save();

        return $dynamic;
    }
}